﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.ComponentModel;

using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api.Domain;
using Top.Api.Util;

using System.Data;
using System.Data.SqlClient;


namespace TopApp.Library
{
    class InventorySyn : BackgroundWorker
    {
        private ITopClient client;
        private Properties.Settings settings;

        private DataTable inventory;
        private DataTable items;

        public string exception;

        public InventorySyn()
        {
            settings = Properties.Settings.Default;

            client = new DefaultTopClient(settings.top_api_url, settings.top_app_key, settings.top_app_secret);

            this.WorkerReportsProgress = true;
            this.WorkerSupportsCancellation = true;

            this.inventory = new DataTable();
            this.items = new DataTable();

            this.initKISInventory();
            this.initKISItems();

            this.DoWork += doIt;
        }

        private void doIt(object sender, DoWorkEventArgs e)
        {
            //查找所有在售商品

            ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
            req.Fields = "num_iid,outer_id,title";
            req.PageSize = 100L;
            req.PageNo = 1L;
            

            List<Item> items = new List<Item>();

            bool next_page = true;

            do{
                Thread.Sleep(500);
                this.ReportProgress(10,"正在获取第" + req.PageNo.ToString()+ "页");
                ItemsOnsaleGetResponse response = client.Execute(req, settings.top_session_key);
                if (response.IsError)
                {
                    this.CancelAsync();
                    return;
                }

                if (response.Items.Count > 0)
                {
                    items.AddRange(response.Items);
                    req.PageNo++;
                }
                else next_page =false;

            } while (next_page);

            for (int i=0; i < items.Count;i++ )
            {
                Thread.Sleep(500);
                items[i] = this.getFullTaobaoItem(items[i]);
            }

            foreach (Item item in items)
            {
                Thread.Sleep(500);
                this.setTaobaoInventory(item);
            }

            this.ReportProgress(100, "同步已完成，共处理了" + items.Count.ToString() + "个商品的库存数量。");

        }

        private void initKISInventory()
        {
            SqlConnection conn = new SqlConnection("Data Source=" + Properties.Settings.Default.kis_database_host + ";UID=" + Properties.Settings.Default.kis_database_user + ";PWD=" + Properties.Settings.Default.kis_database_pswd + ";Initial Catalog=" + Properties.Settings.Default.kis_database_name);

            SqlCommand comm = new SqlCommand(
                "SELECT FItemID, SUM(FQty) AS Qty "+
                "FROM ICInventory "+
                "WHERE (FStockID = "+this.getStockId()+") "+
                "GROUP BY FItemID",
                conn);

            conn.Open();

            SqlDataAdapter adpt = new SqlDataAdapter(comm);
            adpt.Fill(this.inventory);

            conn.Close();
            conn.Dispose();
        }

        private void initKISItems()
        {
            SqlConnection conn = new SqlConnection("Data Source=" + Properties.Settings.Default.kis_database_host + ";UID=" + Properties.Settings.Default.kis_database_user + ";PWD=" + Properties.Settings.Default.kis_database_pswd + ";Initial Catalog=" + Properties.Settings.Default.kis_database_name);

            SqlCommand comm = new SqlCommand(
                "SELECT FItemID,FNumber " +
                "FROM t_ICItem",
                conn);

            conn.Open();

            SqlDataAdapter adpt = new SqlDataAdapter(comm);
            adpt.Fill(this.items);

            conn.Close();
            conn.Dispose();
        }

        private Item getFullTaobaoItem(Item item)
        {
            this.ReportProgress(50, "正在获取商品【" + item.NumIid.ToString() + "】的详情");
            ItemGetRequest req = new ItemGetRequest();
            req.Fields = "num_iid,outer_id,title,sku";
            req.NumIid = item.NumIid;
            ItemGetResponse response = client.Execute(req, settings.top_session_key);
            return response.Item;
        }

        private string getStockId(){

            SqlConnection conn = new SqlConnection("Data Source=" + Properties.Settings.Default.kis_database_host + ";UID=" + Properties.Settings.Default.kis_database_user + ";PWD=" + Properties.Settings.Default.kis_database_pswd + ";Initial Catalog=" + Properties.Settings.Default.kis_database_name);

            SqlCommand comm = new SqlCommand("SELECT FItemID, FName "+
                "FROM t_Stock "+
                "WHERE (FName = '"+settings.kis_taobaoStockName+"')",
                conn);
            conn.Open();

            SqlDataReader reader = comm.ExecuteReader();
            string id = "";
            if (reader.HasRows)
            {
                reader.Read();
                id = reader["FItemID"].ToString();
            }
            else
            {
                this.CancelAsync();
                throw new Exception("错误的仓库名称");
            }

            return id;
        }

        private int getKISInventory(Item item,string outer_id)
        {

            DataRow[] item_rows = this.items.Select("FNumber='" + outer_id + "'");
            string id = "";
            if (item_rows.Count() > 0)
            {
                id = item_rows[0]["FItemID"].ToString();

                DataRow[] inv_rows = this.inventory.Select("FItemID=" + id);

                if (inv_rows.Count() > 0)
                {
                    return Convert.ToInt32( inv_rows[0]["Qty"]);
                }
                else
                {
                    return 0;
                }

            }
            else
            {
                string preStr = "";
                if (item.Skus.Count > 0) preStr = "SKU";

                this.ReportProgress(50, "（！）" + preStr + "商品：【" + outer_id + "（" + item.NumIid + "）】在金蝶中找不到货品");
                return 0;
            }
        }

        private void setTaobaoInventory(Item item)
        {

            List<string> outerIds = new List<string>();

            if (item.Skus.Count == 0)
            {
                outerIds.Add(item.OuterId);
            }
            else
            {
                this.ReportProgress(50, "（SKU）商品【" + item.NumIid.ToString() + "】有" + item.Skus.Count.ToString() + "个SKU库存：");

                foreach(Sku sku in item.Skus){
                    outerIds.Add(sku.OuterId);
                }
            }


            string[] exception_outerid = this.exception.Split("\r\n".ToCharArray());
            bool sy = true;

            foreach (string outerId in outerIds)
            {

                foreach (string outer_id in exception_outerid)
                {
                    if (outer_id == outerId) sy = false;
                }

                if (!sy)
                {
                    this.ReportProgress(50, "（#）商品：【" + outerId + "（" + item.NumIid + "）】在例外列表中，不作同步");

                }
                else
                {

                    ItemQuantityUpdateRequest req = new ItemQuantityUpdateRequest();
                    req.NumIid = item.NumIid;
                    req.Quantity = this.getKISInventory(item,outerId);
                    if (item.Skus.Count > 0) req.OuterId = outerId;
                    ItemQuantityUpdateResponse response = client.Execute(req, settings.top_session_key);

                    if (response.IsError)
                    {
                        this.ReportProgress(50, "商品：【" + outerId + "（" + item.NumIid + "）】同步失败：" + response.ErrCode + " | " + response.ErrMsg);
                        
                    }
                    else
                    {
                        this.ReportProgress(50, "商品：【" + outerId + "（" + item.NumIid + "）】的库存已同步为：" + req.Quantity.ToString());
                        
                    }

                    //this.ReportProgress(50, "商品：【" + item.OuterId + "（" + item.NumIid + "）】的库存已同步为：" + inv.ToString());
                    

                }

            }
        }
    }
}

